package com.hunt.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hunt.dao.TransactionCalendarMapper;
import com.hunt.model.app.*;
import com.hunt.model.dto.*;
import com.hunt.model.entity.*;
import com.hunt.service.AppStockDataService;
import com.hunt.service.KLineMessageService;
import com.hunt.service.app.FinancialDataService;
import com.hunt.service.app.QuotationsFinancialService;
import com.hunt.service.app.QuotationsFlowService;
import com.hunt.util.MDKLineResponse;
import com.hunt.util.SplitKLineRes;
import com.hunt.util.Result;
import com.hunt.util.WMKLineResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static com.hunt.util.SystemConstant.*;

/**
 * @Author: sjs
 * @Date : 2020/9/22 16:15
 */
@Api(value = "手机app端,股票数据管理模块")
@Controller
@RequestMapping(path = "/app/stockData")
public class AppStockDataController{


    private static final Logger log = LoggerFactory.getLogger(AppStockDataController.class);

    @Autowired
    @Resource
    private AppStockDataService appStockDataService;

    @Autowired
    @Resource
    private KLineMessageService kLineMessageService;

    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private TransactionCalendarMapper transactionCalendarMapper;
    @Resource
    private RedisTemplate stringredisTemplate;

    @ApiOperation(value = "查询最近10条分笔数据(手机端明细列表)", httpMethod = "POST",consumes="application/json", produces = "application/json", response = SplitKLineRes.class )
    @ApiImplicitParams({
            @ApiImplicitParam(name = "limit", value = "limit", dataType = "Integer", paramType = "query",required = false),
            @ApiImplicitParam(name = "field[]", value = "field[]", allowMultiple=true,dataType = "String", paramType = "query",required = false),
            @ApiImplicitParam(name = "symbol[]", value = "symbol[]", allowMultiple=true,dataType = "String", paramType = "query",required = true)
    })
    @ResponseBody
    @RequestMapping(value = "findRecentMinData", method = RequestMethod.POST)
    public SplitKLineRes findRecentMinData(@RequestParam(value = "limit", defaultValue = "9", required = false) Integer limit,
                                           @RequestParam(value = "field[]" ,required = false) List<String> field,
                                           @RequestParam(value = "symbol[]") List<String> symbol
    ) {
        long startTime = System.currentTimeMillis();

        SplitKLineRes kLineRes = new SplitKLineRes();
        List<HqStockData> redisDataList = appStockDataService.findRecentMinData(symbol.get(0), limit);
        ArrayList<SKLineVO> skLineVOList = new ArrayList<>();
        ArrayList<DealVO> dealList = new ArrayList<>();
        List<Object> emptyList = new ArrayList<>();
        SKLineVO skLineVO = new SKLineVO();
        if (redisDataList.size() != 0) {

            HqStockData hqStockNewest = redisDataList.get(0);

            String dateTimeStr = hqStockNewest.getDateTime();
            String strPre = dateTimeStr.substring(0, 8);
            String strBack = dateTimeStr.substring(8, 14);

            for (HqStockData hqStockData : redisDataList) {
                DealVO dealVO = new DealVO();
                String bsStr = hqStockData.getBs();
                dealVO.setBs(Integer.parseInt(bsStr));
                dealVO.setPrice(hqStockData.getNewPrice());
                dealVO.setAmount(hqStockData.getNumTrades());
                dealVO.setVol(hqStockData.getVol());

                String dateTime = hqStockData.getDateTime();
                String time = dateTime.substring(8, 14);
                dealVO.setTime(Long.parseLong(time));

                dealList.add(dealVO);
            }
            skLineVO.setDeal(dealList);
            skLineVO.setTime(Long.parseLong(strBack));
            skLineVO.setDate(Long.parseLong(strPre));
            skLineVO.setPrice(hqStockNewest.getNewPrice());
            skLineVO.setHigh(hqStockNewest.getHigh());
            skLineVO.setLow(hqStockNewest.getLow());
            skLineVO.setAmount(0);
            skLineVO.setVol(0);
            skLineVO.setIncrease(0);
            skLineVO.setName(null);
            skLineVO.setSymbol(symbol.get(0));

            skLineVOList.add(skLineVO);
            kLineRes.setStock(skLineVOList);


        } else {
            kLineRes.setStock(emptyList);
        }
        kLineRes.setStart(0);
        kLineRes.setEnd(20);
        kLineRes.setCount(limit);
        long endTime = System.currentTimeMillis();
        kLineRes.setTicket((int) (endTime - startTime));
        kLineRes.setVersion("HQ.Stock 1.0");
        kLineRes.setMessage("加载版块");
        kLineRes.setCode(0);
        DateTimeFormatter fmTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //当前时间
        LocalDateTime nowLocalTime = LocalDateTime.now();
        String serverTimeStr = nowLocalTime.format(fmTime);
        kLineRes.setServerTime(serverTimeStr);
        return kLineRes;
    }

    @ApiOperation(value = "查询股票分钟K线数据", httpMethod = "POST",consumes="application/json", produces = "application/json", response = MDKLineResponse.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "field[]", allowMultiple=true,value = "field数组", dataType = "String", paramType = "query",required = false),
            @ApiImplicitParam(name = "symbol", allowMultiple=true,value = "symbol", dataType = "String", paramType = "query",required = true),
            @ApiImplicitParam(name = "start", value = "start", dataType = "Integer", paramType = "query",required = false),
            @ApiImplicitParam(name = "count", value = "count", dataType = "Integer", paramType = "query",required = false)
    })
    @ResponseBody
    @RequestMapping(value = "getMinKLineData", method = RequestMethod.POST)
    public MDKLineResponse getMinKLineData(@RequestParam(value = "field[]", required = false) List<String> field,
                                           @RequestParam List<String> symbol,
                                           @RequestParam(defaultValue = "0", required = false) Integer start,
                                           @RequestParam(defaultValue = "10", required = false) Integer count
            /*
                                       @RequestParam (value = "Count",defaultValue = "", required = false) field[] name,
                                       @RequestParam (value = "Field",defaultValue = "", required = false) field[] symbol,
                                       @RequestParam (value = "Period",defaultValue = "", required = false) field[] yclose,
                                       @RequestParam (value = "RigheType",defaultValue = "", required = false) field[] open,
                                       @RequestParam (value = "RigheType",defaultValue = "", required = false) field[] price,
                                       @RequestParam (value = "RigheType",defaultValue = "", required = false) field[] high,
                                       @RequestParam (value = "RigheType",defaultValue = "", required = false) field[] low,
                                       @RequestParam (value = "RigheType",defaultValue = "", required = false) field[] vol
                                      */
    ) {
        long startSysTime = System.currentTimeMillis();
        MDKLineResponse minKLineResVO = new MDKLineResponse();
        long endSysTime = System.currentTimeMillis();
        Object obj = stringredisTemplate.opsForHash().get("Real_time_Stock_Data", symbol.get(0));

        List<List<Object>> minDataList = new ArrayList<>();
        //获取该股票的分钟K线
        List<MinKLine> minKLineList = kLineMessageService.findMinKLineDataFromMongo(symbol.get(0), start, count);
        if (minKLineList != null && minKLineList.size() != 0) {
            Collections.reverse(minKLineList);
            for (MinKLine minKLine : minKLineList) {
                List<Object> minDataVO = new ArrayList<>();
                String dateTimeStr = String.valueOf(minKLine.get_id());
                String dataTimePre = dateTimeStr.substring(0, 8);
                String strBack = dateTimeStr.substring(8, 12);

                minDataVO.add(Long.parseLong(dataTimePre));
                minDataVO.add(minKLine.getOpen());
                minDataVO.add(minKLine.getOpen());
                minDataVO.add(minKLine.getHigh());
                minDataVO.add(minKLine.getLow());
                minDataVO.add(minKLine.getClose());
                minDataVO.add(minKLine.getVol());
                minDataVO.add(minKLine.getMoney());
                minDataVO.add(Long.parseLong(strBack));
                minDataList.add(minDataVO);
            }
        }
        minKLineResVO.setData(minDataList);
        minKLineResVO.setSymbol(symbol.get(0));
        minKLineResVO.setName("浦发银行");
        minKLineResVO.setStart(start);
        minKLineResVO.setEnd(start + count);
        minKLineResVO.setCount(count);
        minKLineResVO.setTicket((int) (endSysTime - startSysTime));
        minKLineResVO.setVersion("2.0");
        minKLineResVO.setMessage(null);
        minKLineResVO.setCode(0);

        DateTimeFormatter fmTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //当前时间
        LocalDateTime nowLocalTime = LocalDateTime.now();
        String serverTimeStr = nowLocalTime.format(fmTime);
        minKLineResVO.setServertime(serverTimeStr);
        return minKLineResVO;
    }

    @ApiOperation(value = "查询股票日k线数据", httpMethod = "POST",consumes="application/json", produces = "application/json", response = MDKLineResponse.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "field[]",allowMultiple=true, value = "field数组", dataType = "String", paramType = "query",required = false),
            @ApiImplicitParam(name = "symbol", allowMultiple=true,value = "symbol", dataType = "String", paramType = "query",required = true),
            @ApiImplicitParam(name = "start", value = "start", dataType = "Integer", paramType = "query",required = false),
            @ApiImplicitParam(name = "count", value = "count", dataType = "Integer", paramType = "query",required = false),
            @ApiImplicitParam(name = "right", value = "right", dataType = "Integer", paramType = "query",required  = false),

    })
    @ResponseBody
    @RequestMapping(value = "getDayKLineData", method = RequestMethod.POST)
    public MDKLineResponse getDayKLineData(@RequestParam(value = "field[]",required = false) List<String> field,
                                           @RequestParam List<String> symbol,
                                           @RequestParam(defaultValue = "0", required = false) Integer start,
                                           @RequestParam(defaultValue = "10", required = false) Integer count,
                                           @RequestParam(defaultValue = "0", required = false) Integer right
   
    ) {
        long startSysTime = System.currentTimeMillis();//获取当前系统时间(毫秒)

        MDKLineResponse dayKLineVO = new MDKLineResponse();
        dayKLineVO.setName("先导智能");
        dayKLineVO.setSymbol(symbol.get(0));
        dayKLineVO.setStart(start);
        dayKLineVO.setEnd(start + count);
        dayKLineVO.setCount(count);
        long endSysTime = System.currentTimeMillis();
        dayKLineVO.setTicket((int) (endSysTime - startSysTime));
        dayKLineVO.setVersion("1.0");
        dayKLineVO.setMessage(null);
        dayKLineVO.setCode(0);
        DateTimeFormatter fmTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String serverTimeStr = LocalDateTime.now().format(fmTime);
        dayKLineVO.setServertime(serverTimeStr);
        //查询当前股票的日k数据
        List<DayKLine> dayKLineList = kLineMessageService.getDayKLineDataFromMongo(symbol.get(0), start, count);
        //如果数据库里有值
        if(dayKLineList !=null && dayKLineList.size() > 0) {
            List<List<Object>> dataList = new ArrayList<>();
            for (DayKLine mdayKLine : dayKLineList) {
                List<Object> mData = new ArrayList<>();
                if(right==0){
                    mData.add(mdayKLine.get_id());
                    mData.add(mdayKLine.getPreClose());
                    mData.add(mdayKLine.getOpen());
                    mData.add(mdayKLine.getHigh());
                    mData.add(mdayKLine.getLow());
                    mData.add(mdayKLine.getClose());
                    mData.add(mdayKLine.getVol()*100);
                    mData.add(mdayKLine.getMoney());
                }
                if(right==1){
                    mData.add(mdayKLine.get_id());
                    mData.add(mdayKLine.getFrontPreClose());
                    mData.add(mdayKLine.getFrontOpen());
                    mData.add(mdayKLine.getFrontHigh());
                    mData.add(mdayKLine.getFrontLow());
                    mData.add(mdayKLine.getFrontClose());
                    mData.add(mdayKLine.getVol()*100);
                    mData.add(mdayKLine.getMoney());
                }
                if(right==2){
                    mData.add(mdayKLine.get_id());
                    mData.add(mdayKLine.getBackPreClose());
                    mData.add(mdayKLine.getBackOpen());
                    mData.add(mdayKLine.getBackHigh());
                    mData.add(mdayKLine.getBackLow());
                    mData.add(mdayKLine.getBackClose());
                    mData.add(mdayKLine.getVol()*100);
                    mData.add(mdayKLine.getMoney());
                }
                dataList.add(mData);
            }
            Collections.reverse(dataList);
            dayKLineVO.setData(dataList);

            //获取最近一条数据的时间:今天日K用实时行情,之后把复权因子计算一下
            String mDayLastStr = String.valueOf(dataList.get(dataList.size() - 1).get(0));
            String todayStr = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
            List<Object> todayKLine = new ArrayList<>();
            if (mDayLastStr.equals(todayStr)) {
                dataList.remove(dataList.size() - 1);
            }
                //获取实时行情
                HqStockDataInfo hqStockDataNew = appStockDataService.getRecentMinDataNew(symbol.get(0));
                if (hqStockDataNew != null && LocalTime.parse(hqStockDataNew.getDateTime().substring(8,14),LOCAL_TIME_FORMATTER).isAfter(HQ_OPEN)) {
                    //如果实时行情数据不是今天的,说明今天不是交易日
                    if (hqStockDataNew.getDateTime().substring(0,8).equals(todayStr)){
                        String todayTime = hqStockDataNew.getDateTime().substring(0, 8);
                        todayKLine.add(Long.parseLong(todayTime));
                        if(right==0){
                            todayKLine.add(hqStockDataNew.getPreClose());
                            todayKLine.add(hqStockDataNew.getOpen());
                            todayKLine.add(hqStockDataNew.getHigh());
                            todayKLine.add(hqStockDataNew.getLow());
                            todayKLine.add(hqStockDataNew.getNewPrice());
                            todayKLine.add(hqStockDataNew.getVol()*100);
                            todayKLine.add(hqStockDataNew.getMoney());
                        }
                        if(right==1){
                            List<Double> needcount=new LinkedList();
                            needcount.add(Double.valueOf(hqStockDataNew.getPreClose()));
                            needcount.add(Double.valueOf(hqStockDataNew.getOpen()));
                            needcount.add(Double.valueOf(hqStockDataNew.getHigh()));
                            needcount.add(Double.valueOf(hqStockDataNew.getLow()));
                            needcount.add(Double.valueOf(hqStockDataNew.getNewPrice()));
                            needcount=kLineMessageService.rehabilitationcountfront(needcount,symbol.get(0));
                            for(Double d:needcount){
                                todayKLine.add(d);
                            }
                            todayKLine.add(hqStockDataNew.getVol()*100);
                            todayKLine.add(hqStockDataNew.getMoney());
                        }
                        if(right==2){
                            List<Double> needcount=new LinkedList();
                            needcount.add(Double.valueOf(hqStockDataNew.getPreClose()));
                            needcount.add(Double.valueOf(hqStockDataNew.getOpen()));
                            needcount.add(Double.valueOf(hqStockDataNew.getHigh()));
                            needcount.add(Double.valueOf(hqStockDataNew.getLow()));
                            needcount.add(Double.valueOf(hqStockDataNew.getNewPrice()));

                            needcount=kLineMessageService.rehabilitationcountback(needcount,symbol.get(0));
                            for(Double d:needcount){
                                todayKLine.add(d);
                            }
                            todayKLine.add(hqStockDataNew.getVol()*100);
                            todayKLine.add(hqStockDataNew.getMoney());
                        }
                        dataList.add(todayKLine);
                    }
                }
            return dayKLineVO;
        } else {
            List<List<Object>> dataListToRedis = new ArrayList<>();
            List<Object> hqStockList = new ArrayList<>();
            HqStockDataInfo hqStockFromRedis = appStockDataService.getRecentMinDataNew(symbol.get(0));
            String todayTime = hqStockFromRedis.getDateTime().substring(0, 8);
            hqStockList.add(Long.parseLong(todayTime));
            if(right==0){
                hqStockList.add(hqStockFromRedis.getPreClose());
                hqStockList.add(hqStockFromRedis.getOpen());
                hqStockList.add(hqStockFromRedis.getHigh());
                hqStockList.add(hqStockFromRedis.getLow());
                hqStockList.add(hqStockFromRedis.getNewPrice());
                hqStockList.add(hqStockFromRedis.getVol()*100);
                hqStockList.add(hqStockFromRedis.getMoney());
            }
            if(right==1){
                List<Double> needcount=new LinkedList();
                needcount.add(Double.valueOf(hqStockFromRedis.getPreClose()));
                needcount.add(Double.valueOf(hqStockFromRedis.getOpen()));
                needcount.add(Double.valueOf(hqStockFromRedis.getHigh()));
                needcount.add(Double.valueOf(hqStockFromRedis.getLow()));
                needcount.add(Double.valueOf(hqStockFromRedis.getNewPrice()));

                needcount=kLineMessageService.rehabilitationcountfront(needcount,symbol.get(0));
                for(Double d:needcount){
                    hqStockList.add(d);
                }
                hqStockList.add(hqStockFromRedis.getVol()*100);
                hqStockList.add(hqStockFromRedis.getMoney());
            }
            if(right==2){
                List<Double> needcount=new LinkedList();
                needcount.add(Double.valueOf(hqStockFromRedis.getPreClose()));
                needcount.add(Double.valueOf(hqStockFromRedis.getOpen()));
                needcount.add(Double.valueOf(hqStockFromRedis.getHigh()));
                needcount.add(Double.valueOf(hqStockFromRedis.getLow()));
                needcount.add(Double.valueOf(hqStockFromRedis.getNewPrice()));

                needcount=kLineMessageService.rehabilitationcountback(needcount,symbol.get(0));
                for(Double d:needcount){
                    hqStockList.add(d);
                }
                hqStockList.add(hqStockFromRedis.getVol()*100);
                hqStockList.add(hqStockFromRedis.getMoney());
            }
            dataListToRedis.add(hqStockList);
            dayKLineVO.setData(dataListToRedis);
        }
        return dayKLineVO;
    }

    @ApiOperation(value = "查询最新五档买卖", httpMethod = "POST",consumes="application/json", produces = "application/json", response = BuySellEntity.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "field[]", allowMultiple=true,value = "field数组", dataType = "String", paramType = "query",required = false),
            @ApiImplicitParam(name = "symbol[]", allowMultiple=true,value = "symbol数组", dataType = "String", paramType = "query",required = true),
    })
    @ResponseBody

    @RequestMapping(value = "getStockRealTime", method = RequestMethod.POST )
    public BuySellEntity getStockRealTime(@RequestParam(value = "field[]",required = false) List<String> field,
                                          @RequestParam(value = "symbol[]") List<String> symbol
    ) {
        //9点到9点14不返回数据
       if(isemptytime()&&istransaction()){
           return  new BuySellEntity();
       }
       else {
           //从redis里面取出数据
           return appStockDataService.getStockRealTime(symbol.get(0));
       }
    }

//    /**
//     *  查询股票分钟数据
//     *
//     * @param symbol         股票代码
//     * @param start          起始位置索引 -1 从最近下载
//     * @param count          下载个数
//     * @param field          集合
//     * @param Period         日线周期 0=日线 1=周 2=月 分钟周期 0=1分钟 1=5分钟 2=15分钟 3=30分钟
//     * @param RigheType      复权类型
//     * @return
//     */
    @ApiOperation(value = "查询股票实时分时数据", httpMethod = "POST",consumes="application/json", produces = "application/json", response = SplitKLineRes.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "field[]",allowMultiple=true, value = "field数组", dataType = "String", paramType = "query",required = false),
            @ApiImplicitParam(name = "symbol[]", allowMultiple=true,value = "symbol数组", dataType = "String", paramType = "query",required = true),
    })
    @ResponseBody
    @RequestMapping(value = "getStockMinData", method = RequestMethod.POST)
    public SplitKLineRes getStockMinData(@RequestParam(value = "field[]",required = false) List<String> field,
                                         @RequestParam(value = "symbol[]") List<String> symbol
                                         //股票代码 //form参数
                                           /*@RequestParam (value = "Start",defaultValue = "", required = false) Integer start,
                                           @RequestParam (value = "Count",defaultValue = "", required = false) Integer count,
                                           @RequestParam (value = "Field",defaultValue = "", required = false) String[] field,
                                           @RequestParam (value = "Period",defaultValue = "", required = false) Integer Period,
                                           @RequestParam (value = "RigheType",defaultValue = "", required = false) Integer RigheType,
                                           @RequestParam (value = "address",defaultValue = "", required = false) String address*/) {
        return appStockDataService.getStockMinData(symbol);
    }


    @ApiOperation(value = "查询指数日k线数据", httpMethod = "POST",consumes="application/json", produces = "application/json", response = WMKLineResponse.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "field[]",allowMultiple=true, value = "field数组", dataType = "String", paramType = "query",required = false),
            @ApiImplicitParam(name = "symbol", allowMultiple=true,value = "symbol", dataType = "String", paramType = "query",required = true),
            @ApiImplicitParam(name = "start", value = "start", dataType = "Integer", paramType = "query",required = false),
            @ApiImplicitParam(name = "count", value = "count", dataType = "Integer", paramType = "query",required = false),
    })
    @ResponseBody
    @RequestMapping(value = "getIndexDayKLineData", method = RequestMethod.POST)
    public WMKLineResponse getIndexDayKLineData(@RequestParam(value = "field[]",required = false) List<String> field,
                                           @RequestParam List<String> symbol,
                                           @RequestParam(defaultValue = "0", required = false) Integer start,
                                           @RequestParam(defaultValue = "10", required = false) Integer count
    ) {
        long startSysTime = System.currentTimeMillis();//获取当前系统时间(毫秒)

        WMKLineResponse dayKLineVO = new WMKLineResponse();
        dayKLineVO.setName("指数日K");
        dayKLineVO.setSymbol(symbol.get(0));
        dayKLineVO.setStart(start);
        dayKLineVO.setEnd(start + count);
        dayKLineVO.setCount(count);
        long endSysTime = System.currentTimeMillis();
        dayKLineVO.setTicket((int) (endSysTime - startSysTime));
        dayKLineVO.setVersion("1.0");
        dayKLineVO.setMessage(null);
        dayKLineVO.setCode(0);
        DateTimeFormatter fmTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String serverTimeStr = LocalDateTime.now().format(fmTime);
        dayKLineVO.setServertime(serverTimeStr);
        //查询当前股票的日k数据
        List<IndexDayKLine> dayKLineList = kLineMessageService.getIndexDayKLineDataFromMongo(symbol.get(0), start, count);
        if(dayKLineList !=null && dayKLineList.size() > 0) {
            List<List<String>> dataList = new ArrayList<>();
            for (IndexDayKLine mdayKLine : dayKLineList) {
                List<String> mData = new ArrayList<>();
                mData.add(String.valueOf(mdayKLine.get_id()));
                mData.add(String.valueOf(mdayKLine.getPreClose()));
                mData.add(String.valueOf(mdayKLine.getOpen()));
                mData.add(String.valueOf(mdayKLine.getHigh()));
                mData.add(String.valueOf(mdayKLine.getLow()));
                mData.add(String.valueOf(mdayKLine.getClose()));
                mData.add(String.valueOf(mdayKLine.getVol()));
                mData.add(String.valueOf(mdayKLine.getMoney()));
                dataList.add(mData);
            }
            Collections.reverse(dataList);
            dayKLineVO.setData(dataList);

            //获取最近一条数据的时间:如果没有今天日K就用实时行情补充
            String mDayLastStr = dataList.get(dataList.size() - 1).get(0);
            String todayStr = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
            //最后一笔不是今天
            if (!mDayLastStr.equals(todayStr)) {
                //获取实时行情
                HqStockDataInfo hqStockDataNew = appStockDataService.getRecentMinDataNew(symbol.get(0));
                if (hqStockDataNew != null) {
                    //如果实时行情数据是今天,并且行情超过9:30,说明今天是交易日,添加K线
                    if (hqStockDataNew.getDateTime().substring(0,8).equals(todayStr) && LocalTime.parse(hqStockDataNew.getDateTime().substring(8,14),LOCAL_TIME_FORMATTER).isAfter(HQ_OPEN)){
                        List<String> todayKLine = new ArrayList<>();
                        String todayTime = hqStockDataNew.getDateTime().substring(0, 8);
                        todayKLine.add(todayTime);
                        todayKLine.add(String.valueOf(hqStockDataNew.getPreClose()));
                        todayKLine.add(String.valueOf(hqStockDataNew.getOpen()));
                        todayKLine.add(String.valueOf(hqStockDataNew.getHigh()));
                        todayKLine.add(String.valueOf(hqStockDataNew.getLow()));
                        todayKLine.add(String.valueOf(hqStockDataNew.getNewPrice()));
                        todayKLine.add(String.valueOf(hqStockDataNew.getVol()));
                        todayKLine.add(String.valueOf(hqStockDataNew.getMoney()));
                        dataList.add(todayKLine);
                    }
                }
            }
            return dayKLineVO;
        } else {
            List<List<String>> dataListToRedis = new ArrayList<>();
            List<String> hqStockList = new ArrayList<>();
            HqStockDataInfo hqStockFromRedis = appStockDataService.getRecentMinDataNew(symbol.get(0));
            String todayTime = hqStockFromRedis.getDateTime().substring(0, 8);
            hqStockList.add(todayTime);
            hqStockList.add(String.valueOf(hqStockFromRedis.getPreClose()));
            hqStockList.add(String.valueOf(hqStockFromRedis.getOpen()));
            hqStockList.add(String.valueOf(hqStockFromRedis.getHigh()));
            hqStockList.add(String.valueOf(hqStockFromRedis.getLow()));
            hqStockList.add(String.valueOf(hqStockFromRedis.getNewPrice()));
            hqStockList.add(String.valueOf(hqStockFromRedis.getVol()));
            hqStockList.add(String.valueOf(hqStockFromRedis.getMoney()));
            dataListToRedis.add(hqStockList);
            dayKLineVO.setData(dataListToRedis);
        }
        return dayKLineVO;
    }

    @ApiOperation(value = "查询指数周k线数据", httpMethod = "POST",consumes="application/json", produces = "application/json", response = WMKLineResponse.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "field[]",allowMultiple=true, value = "field数组", dataType = "String", paramType = "query",required = false),
            @ApiImplicitParam(name = "symbol", allowMultiple=true,value = "symbol", dataType = "String", paramType = "query",required = true),
            @ApiImplicitParam(name = "start", value = "start", dataType = "Integer", paramType = "query",required = false),
            @ApiImplicitParam(name = "count", value = "count", dataType = "Integer", paramType = "query",required = false),
    })
    @ResponseBody
    @RequestMapping(value = "getIndexWeekKData", method = RequestMethod.POST)
    public WMKLineResponse getIndexWeekKData(@RequestParam(value = "field[]",required = false) List<String> field,
                                             @RequestParam List<String> symbol,
                                             @RequestParam(defaultValue = "0", required = false) Integer start,
                                             @RequestParam(defaultValue = "10", required = false) Integer count) {

        long exeStartTime = System.currentTimeMillis();//获取当前系统时间(毫秒)
        WMKLineResponse dayKLineVO = new WMKLineResponse();
        dayKLineVO.setName("深沪指数周K");
        dayKLineVO.setSymbol(symbol.get(0));
        dayKLineVO.setStart(start);
        dayKLineVO.setEnd(start + count);
        dayKLineVO.setCount(count);
        dayKLineVO.setVersion("1.0");
        dayKLineVO.setMessage(null);
        dayKLineVO.setCode(0);
        String serverTimeStr = LocalDateTime.now().format(timeFormatter);
        dayKLineVO.setServertime(serverTimeStr);
        //查询当前指数的周k数据
        List<WeekMonthKLine> weekLines = kLineMessageService.getIndexWeekLine(symbol.get(0),start,count);
        long exeEndTime = System.currentTimeMillis();
        dayKLineVO.setTicket((int) (exeEndTime - exeStartTime));

        if (weekLines == null || weekLines.size() == 0){
            List<List<String>> data = new ArrayList<>();
            List<String> data_info = new ArrayList<>();
            HqStockDataInfo hq_shot = appStockDataService.getRecentMinDataNew(symbol.get(0));
            if (hq_shot == null){
                for (int i = 0; i < 8; i++) {
                    data_info.add("0");
                }
                data.add(data_info);
                dayKLineVO.setData(data);
                return dayKLineVO;
            }
            String todayTime = hq_shot.getDateTime().substring(0, 8);
            data_info.add(todayTime);
            data_info.add(String.valueOf(hq_shot.getPreClose()));
            data_info.add(String.valueOf(hq_shot.getOpen()));
            data_info.add(String.valueOf(hq_shot.getHigh()));
            data_info.add(String.valueOf(hq_shot.getLow()));
            data_info.add(String.valueOf(hq_shot.getNewPrice()));
            data_info.add(String.valueOf(hq_shot.getVol()));
            data_info.add(String.valueOf(hq_shot.getMoney()));
            data.add(data_info);
            dayKLineVO.setData(data);
            return dayKLineVO;
        }else{
            List<List<String>> data = new ArrayList<>();
            for (WeekMonthKLine weekLine : weekLines) {
                List<String> data_info = new ArrayList<>();
                data_info.add(weekLine.get_id());
                data_info.add(String.valueOf(weekLine.getPreClose()));
                data_info.add(String.valueOf(weekLine.getOpen()));
                data_info.add(String.valueOf(weekLine.getHigh()));
                data_info.add(String.valueOf(weekLine.getLow()));
                data_info.add(String.valueOf(weekLine.getClose()));
                data_info.add(String.valueOf(weekLine.getVol()));
                data_info.add(String.valueOf(weekLine.getMoney()));
                data.add(data_info);
            }

            HqStockDataInfo hq_shot = appStockDataService.getRecentMinDataNew(symbol.get(0));
            if (hq_shot == null || LocalTime.parse(hq_shot.getDateTime().substring(8,14),LOCAL_TIME_FORMATTER).isBefore(HQ_OPEN)){
                Collections.reverse(data);
                dayKLineVO.setData(data);
                return dayKLineVO;
            }
            //开始判断是不是同一周
            LocalDate hisDataTime = LocalDate.parse(String.valueOf(data.get(0).get(0)), fmTime);
            LocalDate hqDataTime = LocalDate.parse(hq_shot.getDateTime().substring(0, 8), fmTime);
            //是同一周  两个时间均为7天之内 并且
            if (isSameWeek(hisDataTime,hqDataTime)){
                //不是同一天参与计算
                if (!hq_shot.getDateTime().substring(0,8).equals(String.valueOf(data.get(0).get(0)))){
                    List<String> new_week_line = data.get(0);
                    new_week_line.set(0,hq_shot.getDateTime().substring(0,8));//更新日期
                    //new_week_line.set(1,);//昨收不用更新
                    //new_week_line.set(2,);//开 不用更新
                    new_week_line.set(3,hq_shot.getNewPrice() > Float.valueOf(data.get(0).get(3))? String.valueOf(hq_shot.getNewPrice()):data.get(0).get(3));//高
                    new_week_line.set(4,hq_shot.getNewPrice() < Float.valueOf(data.get(0).get(4))? String.valueOf(hq_shot.getNewPrice()):data.get(0).get(4));//低
                    new_week_line.set(5,String.valueOf(hq_shot.getNewPrice()));//收
                    new_week_line.set(6,String.valueOf(hq_shot.getVol()+Long.valueOf(data.get(0).get(6))));
                    new_week_line.set(7,String.valueOf(hq_shot.getVol()+Long.valueOf(data.get(0).get(7))));
                }
                //不是同一周
            }else{
                List<String> data_info = new ArrayList<>();
                String todayTime = hq_shot.getDateTime().substring(0, 8);
                data_info.add(todayTime);
                data_info.add(String.valueOf(hq_shot.getPreClose()));
                data_info.add(String.valueOf(hq_shot.getOpen()));
                data_info.add(String.valueOf(hq_shot.getHigh()));
                data_info.add(String.valueOf(hq_shot.getLow()));
                data_info.add(String.valueOf(hq_shot.getNewPrice()));
                data_info.add(String.valueOf(hq_shot.getVol()));
                data_info.add(String.valueOf(hq_shot.getMoney()));
                Collections.reverse(data);
                data.add(data_info);
                dayKLineVO.setData(data);
                return dayKLineVO;
            }
            Collections.reverse(data);
            dayKLineVO.setData(data);
            return dayKLineVO;
        }
    }

    @ApiOperation(value = "查询指数月k线数据", httpMethod = "POST",consumes="application/json", produces = "application/json", response = WMKLineResponse.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "field[]",allowMultiple=true, value = "field数组", dataType = "String", paramType = "query",required = false),
            @ApiImplicitParam(name = "symbol", allowMultiple=true,value = "symbol", dataType = "String", paramType = "query",required = true),
            @ApiImplicitParam(name = "start", value = "start", dataType = "Integer", paramType = "query",required = false),
            @ApiImplicitParam(name = "count", value = "count", dataType = "Integer", paramType = "query",required = false),
    })
    @ResponseBody
    @RequestMapping(value = "getIndexMonthKData", method = RequestMethod.POST)
    public WMKLineResponse getIndexMonthKData(@RequestParam(value = "field[]",required = false) List<String> field,
                                              @RequestParam List<String> symbol,
                                              @RequestParam(defaultValue = "0", required = false) Integer start,
                                              @RequestParam(defaultValue = "10", required = false) Integer count) {

        long exeStartTime = System.currentTimeMillis();//获取当前系统时间(毫秒)
        WMKLineResponse dayKLineVO = new WMKLineResponse();
        dayKLineVO.setName("深沪指数月K");
        dayKLineVO.setSymbol(symbol.get(0));
        dayKLineVO.setStart(start);
        dayKLineVO.setEnd(start + count);
        dayKLineVO.setCount(count);
        dayKLineVO.setVersion("1.0");
        dayKLineVO.setMessage(null);
        dayKLineVO.setCode(0);
        String serverTimeStr = LocalDateTime.now().format(timeFormatter);
        dayKLineVO.setServertime(serverTimeStr);
        //查询当前指数的月k数据
        List<WeekMonthKLine> monthLines = kLineMessageService.getIndexMonthLine(symbol.get(0),start,count);
        long exeEndTime = System.currentTimeMillis();
        dayKLineVO.setTicket((int) (exeEndTime - exeStartTime));

        if (monthLines == null || monthLines.size() == 0){
            List<List<String>> data = new ArrayList<>();
            List<String> data_info = new ArrayList<>();
            HqStockDataInfo hq_shot = appStockDataService.getRecentMinDataNew(symbol.get(0));
            if (hq_shot == null){
                for (int i = 0; i < 8; i++) {
                    data_info.add("0");
                }
                data.add(data_info);
                dayKLineVO.setData(data);
                return dayKLineVO;
            }
            String todayTime = hq_shot.getDateTime().substring(0, 8);
            data_info.add(todayTime);
            data_info.add(String.valueOf(hq_shot.getPreClose()));
            data_info.add(String.valueOf(hq_shot.getOpen()));
            data_info.add(String.valueOf(hq_shot.getHigh()));
            data_info.add(String.valueOf(hq_shot.getLow()));
            data_info.add(String.valueOf(hq_shot.getNewPrice()));
            data_info.add(String.valueOf(hq_shot.getVol()));
            data_info.add(String.valueOf(hq_shot.getMoney()));
            data.add(data_info);
            dayKLineVO.setData(data);
            return dayKLineVO;
        }else{
            List<List<String>> data = new ArrayList<>();
            for (WeekMonthKLine monthLine : monthLines) {
                List<String> data_info = new ArrayList<>();
                data_info.add(monthLine.get_id());
                data_info.add(String.valueOf(monthLine.getPreClose()));
                data_info.add(String.valueOf(monthLine.getOpen()));
                data_info.add(String.valueOf(monthLine.getHigh()));
                data_info.add(String.valueOf(monthLine.getLow()));
                data_info.add(String.valueOf(monthLine.getClose()));
                data_info.add(String.valueOf(monthLine.getVol()));
                data_info.add(String.valueOf(monthLine.getMoney()));
                data.add(data_info);
            }

            HqStockDataInfo hq_shot = appStockDataService.getRecentMinDataNew(symbol.get(0));
            if (hq_shot == null || LocalTime.parse(hq_shot.getDateTime().substring(8,14),LOCAL_TIME_FORMATTER).isBefore(HQ_OPEN)){
                Collections.reverse(data);
                dayKLineVO.setData(data);
                return dayKLineVO;
            }

            //是同一月
            if (hq_shot.getDateTime().substring(4,6).equals(String.valueOf(data.get(0).get(0)).substring(4,6))){
                //不是同一天参与计算
                if (!hq_shot.getDateTime().substring(0,8).equals(String.valueOf(data.get(data.size()-1).get(0)))){
                    List<String> new_week_line = data.get(0);
                    new_week_line.set(0,hq_shot.getDateTime().substring(0,8));//更新日期
                    //new_week_line.set(1,);//昨收不用更新
                    //new_week_line.set(2,);//开 不用更新
                    new_week_line.set(3,hq_shot.getNewPrice() > Float.valueOf(data.get(0).get(3)) ? String.valueOf(hq_shot.getNewPrice()):data.get(0).get(3));//高
                    new_week_line.set(4,hq_shot.getNewPrice() < Float.valueOf(data.get(0).get(4)) ? String.valueOf(hq_shot.getNewPrice()):data.get(0).get(4));//低
                    new_week_line.set(5,String.valueOf(hq_shot.getNewPrice()));//收
                    new_week_line.set(6,String.valueOf(hq_shot.getVol()+Long.valueOf(data.get(0).get(6)) ));
                    new_week_line.set(7,String.valueOf(hq_shot.getVol()+Long.valueOf( data.get(0).get(7))));
                }
                //不是同一月
            }else{
                List<String> data_info = new ArrayList<>();
                String todayTime = hq_shot.getDateTime().substring(0, 8);
                data_info.add(todayTime);
                data_info.add(String.valueOf(hq_shot.getPreClose()));
                data_info.add(String.valueOf(hq_shot.getOpen()));
                data_info.add(String.valueOf(hq_shot.getHigh()));
                data_info.add(String.valueOf(hq_shot.getLow()));
                data_info.add(String.valueOf(hq_shot.getNewPrice()));
                data_info.add(String.valueOf(hq_shot.getVol()));
                data_info.add(String.valueOf(hq_shot.getMoney()));
                Collections.reverse(data);
                data.add(data_info);
                dayKLineVO.setData(data);
                return dayKLineVO;
            }
            Collections.reverse(data);
            dayKLineVO.setData(data);
            return dayKLineVO;
        }
    }

    private boolean isSameWeek(LocalDate one,LocalDate two){
        long o = one.atStartOfDay().toInstant(ZoneOffset.of("+8")).toEpochMilli();
        long t = two.atStartOfDay().toInstant(ZoneOffset.of("+8")).toEpochMilli();
        BigDecimal o_divide = new BigDecimal(o).divide(WEEK_UNIT,0,BigDecimal.ROUND_HALF_UP);
        BigDecimal t_divide = new BigDecimal(t).divide(WEEK_UNIT,0,BigDecimal.ROUND_HALF_UP);
        return o_divide.equals(t_divide);
    }

//======================================================================================================================================================
    @Autowired
    private FinancialDataService financialDataService;
    @Autowired
    private QuotationsFlowService quotationsFlowService;
    @Autowired
    private QuotationsFinancialService quotationsFinancialService;

    @ApiOperation(value = "同步个股流通盘(httpclient形式请求三方接口同步到数据库)", httpMethod = "GET", produces = "application/json", response = Result.class)
    @ResponseBody
    @RequestMapping(value = "syncQuotationFlow", method = RequestMethod.GET)
    public Result syncQuotationFlow() {
        //获取所有A股股票代码,封装参数
        List<String> allStockCode = financialDataService.findAllStockCode();

        CloseableHttpClient httpClient = null;

        try {
            httpClient = HttpClients.createDefault();

            for (String s : allStockCode) {
                CloseableHttpResponse response = null;
                try {
                    HttpPost httpPost = new HttpPost("https://opensource.zealink.com/API/StockHistoryDay");
                    httpPost.addHeader("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36");
                    ArrayList<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
                    parameters.add(new BasicNameValuePair("symbol[]", s));
                    parameters.add(new BasicNameValuePair("field[]", "capital.a"));
                    httpPost.setEntity(new UrlEncodedFormEntity(parameters));
                    response = httpClient.execute(httpPost);
                    if (response == null)
                        continue;
                    String html = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
                    if (html == null || html.equals(""))
                        continue;
                    try {
                        JSONObject object = JSON.parseObject(html).getJSONArray("stock").getJSONObject(0);
                        String code = object.getString("symbol");
                        QuotationsFlow quotationsFlow = new QuotationsFlow();
                        quotationsFlow.setCode(code);
                        quotationsFlow.setMessage(html);
                        quotationsFlowService.saveOrUpdateQuotationFlow(quotationsFlow);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    if (response != null){
                        response.close();
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (httpClient != null){
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return Result.success(allStockCode);
    }


    @ApiOperation(value = "通过股票代码获取流通盘数据", httpMethod = "POST", produces = "application/json", response = Result.class)
    @ResponseBody
    @RequestMapping(value = "getQuotationFlowByStockCode", method = RequestMethod.POST)
    public JSONObject getQuotationFlowByStockCode(@RequestParam (value = "symbol[]",required = true)List<String> symbol,
                                                  @RequestParam (value = "field[]",required = false)List<String> field,
                                                  @RequestParam (value = "orderfield",required = false)String orderfield) {
        QuotationsFlow quotationsFlow = quotationsFlowService.getQuotationFlowByStockCode(symbol.get(0));
        if (quotationsFlow == null)
            return null;
        return JSON.parseObject(quotationsFlow.getMessage());
    }



    @ApiOperation(value = "同步个股财务数据(httpclient形式请求三方接口同步到数据库)", httpMethod = "GET", produces = "application/json", response = Result.class)
    @ResponseBody
    @RequestMapping(value = "syncStockFinancial", method = RequestMethod.GET)
    public Result syncStockFinancial() {
        //获取所有A股股票代码,封装参数
        List<String> allStockCode = financialDataService.findAllStockCode();

        CloseableHttpClient httpClient = null;

        try {
            httpClient = HttpClients.createDefault();
            for (String s : allStockCode) {
                CloseableHttpResponse response = null;
                try {
                    HttpPost httpPost = new HttpPost("https://opensource.zealink.com/API/Stock");
                    httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
                    ArrayList<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
                    parameters.add(new BasicNameValuePair("field[]", "name"));
                    parameters.add(new BasicNameValuePair("field[]", "symbol"));
                    parameters.add(new BasicNameValuePair("field[]", "marketvalue"));
                    parameters.add(new BasicNameValuePair("field[]", "flowmarketvalue"));
                    parameters.add(new BasicNameValuePair("field[]", "pe"));
                    parameters.add(new BasicNameValuePair("field[]", "pe2"));
                    parameters.add(new BasicNameValuePair("field[]", "pe3"));
                    parameters.add(new BasicNameValuePair("field[]", "pb"));
                    parameters.add(new BasicNameValuePair("field[]", "bookrate"));
                    parameters.add(new BasicNameValuePair("field[]", "bookdiffer"));
                    parameters.add(new BasicNameValuePair("symbol[]", s));
                    httpPost.setEntity(new UrlEncodedFormEntity(parameters));
                    response = httpClient.execute(httpPost);
                    if (response == null)
                        continue;
                    String html = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
                    System.out.println(html);
                    if (html == null || html.equals(""))
                        continue;
                    try {
                        JSONObject object = JSON.parseObject(html).getJSONArray("stock").getJSONObject(0);
                        String code = object.getString("symbol");
                        QuotationsFinancial quotationsFinancial = new QuotationsFinancial();
                        quotationsFinancial.setCode(code);
                        quotationsFinancial.setMessage(html);
                        quotationsFinancialService.saveOrUpdateQuotationFinancial(quotationsFinancial);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    if (response != null){
                        response.close();
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (httpClient != null){
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return Result.success(allStockCode);
    }

    @ApiOperation(value = "通过股票代码获取股票基础数据", httpMethod = "POST", produces = "application/json", response = Result.class)
    @ResponseBody
    @RequestMapping(value = "getQuotationFinancialByStockCode", method = RequestMethod.POST)
    public JSONObject getQuotationFinancialByStockCode(@RequestParam (value = "symbol[]",required = true)List<String> symbol,
                                                       @RequestParam (value = "field[]",required = false)List<String> field) {
        QuotationsFinancial quotationsFinancial = quotationsFinancialService.getQuotationFinancialByStockCode(symbol.get(0));
        if (quotationsFinancial == null)
            return null;
        return JSON.parseObject(quotationsFinancial.getMessage());
    }




    @ApiOperation(value = "同步财务数据(httpclient形式请求三方接口同步到数据库)", httpMethod = "GET", produces = "application/json", response = Result.class)
    @ResponseBody
    @RequestMapping(value = "syncStockFinancialPlus", method = RequestMethod.GET)
    public Result syncStockFinancialPlus() {
        //获取所有A股股票代码,封装参数
        List<String> allStockCode = financialDataService.findAllStockCode();

        CloseableHttpClient httpClient = null;

        try {
            httpClient = HttpClients.createDefault();
            for (String s : allStockCode) {
                CloseableHttpResponse response = null;
                try {
                    HttpPost httpPost = new HttpPost("https://opensource.zealink.com/API/Stock");
                    httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
                    ArrayList<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
                    parameters.add(new BasicNameValuePair("field[]", "name"));
                    parameters.add(new BasicNameValuePair("field[]", "symbol"));
                    parameters.add(new BasicNameValuePair("field[]", "roe"));
                    parameters.add(new BasicNameValuePair("field[]", "finance"));
                    parameters.add(new BasicNameValuePair("symbol[]", s));
                    httpPost.setEntity(new UrlEncodedFormEntity(parameters));
                    response = httpClient.execute(httpPost);
                    if (response == null)
                        continue;
                    String html = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
                    System.out.println(html);
                    if (html == null || html.equals(""))
                        continue;
                    try {
                        JSONObject object = JSON.parseObject(html).getJSONArray("stock").getJSONObject(0);
                        String code = object.getString("symbol");
                        QuotationsFinancialPlus financialPlus = new QuotationsFinancialPlus();
                        financialPlus.setCode(code);
                        financialPlus.setMessage(html);
                        quotationsFinancialService.saveOrUpdateFinancialPlus(financialPlus);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    if (response != null){
                        response.close();
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (httpClient != null){
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return Result.success(allStockCode);
    }

    @ApiOperation(value = "通过股票代码获取股票基础数据", httpMethod = "POST", produces = "application/json", response = Result.class)
    @ResponseBody
    @RequestMapping(value = "getFinancialPlusByStockCode", method = RequestMethod.POST)
    public JSONObject getFinancialPlusByStockCode(@RequestParam (value = "symbol[]",required = true)List<String> symbol,
                                                       @RequestParam (value = "field[]",required = false)List<String> field) {
        QuotationsFinancialPlus financialPlus = quotationsFinancialService.getFinancialPlusByStockCode(symbol.get(0));
        if (financialPlus == null)
            return null;
        return JSON.parseObject(financialPlus.getMessage());
    }


    @ApiOperation(value = "获取实时基础数据(需要计算)", httpMethod = "POST", produces = "application/json", response = Result.class)
    @ResponseBody
    @RequestMapping(value = "getRealtimeFinancialDataByStockCode", method = RequestMethod.POST)
    public RealtimeFinancialData getRealtimeFinancialDataByStockCode(@RequestParam (value = "symbol[]",required = true)List<String> symbol,
                                                  @RequestParam (value = "field[]",required = false)List<String> field) {
        return appStockDataService.getRealtimeFinancialDataByStockCode(symbol.get(0));
    }
    @ApiOperation(value = "获取股票特殊标志", httpMethod = "POST", produces = "application/json", response = Result.class)
    @ResponseBody
    @RequestMapping(value = "getStockSpecialSign", method = RequestMethod.POST)
    public Result getStockSign() {
        return Result.success(appStockDataService.getStockSpecialSign());}
    @ApiOperation(value = "获取股票特殊标志单个", httpMethod = "POST", produces = "application/json", response = Result.class)
    @ResponseBody
    @RequestMapping(value = "getSingleStockSpecialSign", method = RequestMethod.POST)
    public Result getSingleStockSpecialSign(@RequestParam (value = "symbol",required = true)String symbol) {
        return Result.success(appStockDataService.getSingleStockSpecialSign(symbol));
    }
    private  boolean isemptytime(){
        LocalTime now = LocalTime.now();
        return now.isAfter(LocalTime.of(9, 0, 0)) && now.isBefore(LocalTime.of(9, 14, 0));
    }
    private  boolean istransaction(){
        Date date=new Date();
        SimpleDateFormat s=new SimpleDateFormat("yyyyMMdd");
        TransactionCalendar transactionCalendar=transactionCalendarMapper.findByCalDate(s.format(date));
        return transactionCalendar.getIs_open().equals("1");
    }
}
